package org.example.ding.repository;

import org.example.ding.entity.DishCategory;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

/**
 * 菜品分类数据访问层
 */
@Repository
public interface DishCategoryRepository extends JpaRepository<DishCategory, Long> {

    /**
     * 根据名称查找分类
     */
    Optional<DishCategory> findByName(String name);

    /**
     * 根据餐别类型查找分类
     */
    List<DishCategory> findByMealType(DishCategory.MealType mealType);

    /**
     * 根据名称和餐别类型查找分类
     */
    Optional<DishCategory> findByNameAndMealType(String name, DishCategory.MealType mealType);

    /**
     * 检查分类名称是否存在
     */
    boolean existsByName(String name);

    /**
     * 查找所有分类并按名称排序
     */
    List<DishCategory> findAllByOrderByName();

    /**
     * 根据餐别类型查找分类并按名称排序
     */
    List<DishCategory> findByMealTypeOrderByName(DishCategory.MealType mealType);

    /**
     * 统计每个分类下的菜品数量
     */
    @Query("SELECT c.id, c.name, COUNT(d) FROM DishCategory c LEFT JOIN c.dishes d GROUP BY c.id, c.name")
    List<Object[]> findCategoriesWithDishCount();
}
